﻿using System.Text.RegularExpressions;

namespace CSharpPro._1103;

public class UserServiceImpl : IUserService
{
    public bool Register(User user, List<User> userList)
    {
        // 验证用户名格式（复用你原有的正则逻辑）
        if (string.IsNullOrEmpty(user.Username) || user.Username.Length < 3 || user.Username.Length > 15 || !Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_]+$"))
        {
            return false;
        }
        // 验证密码格式（复用你原有的正则逻辑）
        if (string.IsNullOrEmpty(user.Password) || user.Password.Length < 6 || user.Password.Length > 20 || !Regex.IsMatch(user.Password, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$"))
        {
            return false;
        }
        // 检查用户名是否已存在
        foreach (var u in userList)
        {
            if (u.Username == user.Username)
            {
                return false;
            }
        }
        userList.Add(user);
        return true;
    }

    public User Login(string username, string password, List<User> userList)
    {
        foreach (var u in userList)
        {
            if (u.Username == username && u.Password == password)
            {
                return u;
            }
        }
        return null;
    }

    // 复用你原有的“读取密码（隐藏明文）”方法
    public string ReadPassword()
    {
        string password = "";
        ConsoleKeyInfo keyInfo;
        do
        {
            keyInfo = Console.ReadKey(true);
            if (keyInfo.Key == ConsoleKey.Backspace && password.Length > 0)
            {
                password = password.Remove(password.Length - 1);
                Console.Write("\b \b");
            }
            else if (keyInfo.Key != ConsoleKey.Enter)
            {
                password += keyInfo.KeyChar;
                Console.Write("*");
            }
        } while (keyInfo.Key != ConsoleKey.Enter);
        Console.WriteLine();
        return password;
    }
} 